//
//  RJCityWarning.m
//  AirQuality
//
//  Created by Po on 15/5/4.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCityWarning.h"
#import "RJWarningDay.h"
#import "RJCityWarningModel.h"
#import "RJOutCityView.h"
#import "RJWarningAQIView.h"
#import "RJWarningTable.h"
#import "RJWarningFirstView.h"
#import "RJWarningPM25CheckView.h"
#import "RJWarningAQICheckView.h"
#import "RJWarningFirstCheckView.h"
#import "RJWarningSectionView.h"
#import "RJWarningTypeSection.h"
#import "MBProgressHUD+MJ.h"
#import "RJNavBar.h"


@interface RJCityWarning () <RJOutCityViewDelegate, RJWarningTypeSectionDelegate, RJWarningSectionDelegate,UIWebViewDelegate>

@property (retain, nonatomic) RJWarningFather * scrollView;
@property (retain, nonatomic) RJOutCityView * cityTable;
@property (retain, nonatomic) RJCityWarningModel * model;
@property (retain, nonatomic) RJWarningSectionView * sectionView;
@property (retain, nonatomic) RJWarningTypeSection * typeSection;
@property (retain, nonatomic) UILabel * typeLabel;
@property (retain, nonatomic) UILabel * cityLabel;
@property (retain, nonatomic) UIButton * sendButton;

@property (assign, nonatomic) CGFloat textFiledLength;
@property (assign, nonatomic) CGFloat scrollViewY;
@property (assign, nonatomic) BOOL lockChange;
@property (assign, nonatomic) BOOL isCheck;
@property (assign, nonatomic) BOOL isWarningNetDown;
@property (assign, nonatomic) BOOL isCheckNetDown;
@property (assign, nonatomic) BOOL isChangeSection;
//-------------------------------------------------------------------
@property (retain, nonatomic) UIWebView * webView;
@property (strong, nonatomic) NSString *cityName ;

- (void)initData;
- (void)initInterface;
- (void)initNet;

@end

@implementation RJCityWarning

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self initData];
    [self initInterface];
//    [self initNet];
}

#pragma mark - user-defined initialization function
- (void)initData
{
    _isCheck = NO;
    _lockChange = NO;
    _isWarningNetDown = NO;
    _isCheckNetDown = NO;
    _isChangeSection = NO;
    _model.currentPage = 0;
    
    _model = [[RJCityWarningModel alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(touchScrollView) name:@"touchScrollView" object:nil];
}

- (void)initInterface
{
    
    NSUserDefaults *userDefailt = [NSUserDefaults standardUserDefaults];
    NSArray *userInfo = [userDefailt objectForKey:@"userDefailt1"];
    NSString *url = [[NSString stringWithFormat:@"http://www.scnewair.cn:3389/smartadmin/mobileForecastCity.html"] stringByAppendingString:[NSString stringWithFormat:@"?userName=%@",userInfo[0]]];
    if (![RJUserData defaultRJUserData].isProvince) {
        NSUserDefaults *cityName = [NSUserDefaults standardUserDefaults];
        _cityName = [cityName objectForKey:@"cityName1"];
    }
   
    NSString *url1 = [url stringByAppendingString:[NSString stringWithFormat:@"?city=%@",_cityName]];
    RJNavBar *navBar = [[RJNavBar alloc] init];
    [navBar getReturnButton];
    navBar.centerCityLabel.text = @"城市预报";
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,50 ,ScreenWidth, ScreenHeight-50)];
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;//自动对页面进行缩放以适应屏幕
    //            _webView.detectsPhoneNumbers = YES;
//                [_webView loadHTMLString: @"" baseURL: nil];
                [_webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url1]]];
                [self.view addSubview:_webView];
    [self.view addSubview:navBar];
    
    //--------------------------------------------------------------------------
//    [self.backgroundImage setImage:GetImage(@"WarningCityBack@2x.png")];
//    [self.navBar setReturnButtonHidden:NO];
////    [self.navBar.centerTimeLabel setHidden:YES];
//    [self.navBar.centerCityLabel setHidden:YES];
//    CGPoint center = CGPointMake(ScreenWidth / 2, sysNavBarHeight / 2);
//    [self.navBar addSubview:[self getSectionView]];
//    [_sectionView setCenter:center];
//    
//    [self changeScrollViewWithCount:0];
//    [self.mainView addSubview:[self getTypeSection]];
//    [self.view addSubview:[self getSendButton]];
//    [self.view addSubview:[self getCityLabel]];
//    [self.view addSubview:[self getCityTable]];
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WarningTextFiledShow:) name:@"WarningTextShow" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WarningTextFiledHide:) name:@"WarningTextHide" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAllCitys:) name:@"WarningGetAllCitys" object:nil];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD showMessage:@"正在加载..."];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUD];
}

- (void)initNet
{
    NSString * filePath = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"RJCityArray.plist"];
    NSArray * cityData = [NSArray arrayWithContentsOfFile:filePath];
    //是否已经获取到城市数据
    if ([RJUserData defaultRJUserData].isProvince) {
        if (!cityData || [cityData count] == 0) {
            [_model setCitysFilePath:filePath];
        } else {
            NSMutableArray * nameArray = [[NSMutableArray alloc] init];
            NSMutableArray * codeArray = [[NSMutableArray alloc] init];
            NSMutableArray * cityArray = [[NSMutableArray alloc] init];
            for (NSDictionary * dic in cityData) {
                NSString * string = [dic allValues][0];
                [nameArray addObject:string];
                [codeArray addObject:[dic allKeys][0]];
                [cityArray addObject:@{[dic allKeys][0]:string}];
            }
            _model.cityNames = [NSArray arrayWithArray:nameArray];
            _model.cityCodes = [NSArray arrayWithArray:codeArray];
            [_cityTable setData:cityArray];
        }
        _model.currentCityCode = @"5101";
    } else {
        _model.currentCityCode = [RJUserData defaultRJUserData].currentCityCode;
    }
    
    //获取预警数据
    [self initForecastNetWithCityCode:_model.currentCityCode];
}

- (void)initForecastNetWithCityCode:(NSString *)cityCode
{
    RJLoadView * loadView = [[RJLoadView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:loadView];
    _isWarningNetDown = NO;
    //@"http://xsscd.xicp.net:5100/smartadmin/forecast/getForecast"
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].GetForecast  data:@{@"cityCode":cityCode} completeBlock:^(id responseObject) {
        NSDictionary * data = responseObject[@"data"];
        [_model setWarningData:data];
        [self setDataWithPage:_model.currentPage];
        [loadView removeFromSuperview];
        _isWarningNetDown = YES;
    }failBlack:^(id response) {
        
    }];
}

- (void)initForecastAuditNetWithCityCode:(NSString *)cityCode
{
    //获得时间戳
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * day = [RJTools getTimeWithFormat:@"yyyy-MM-dd"];
    NSDate * date = [formatter dateFromString:day];
    NSTimeInterval time = [date timeIntervalSince1970];
    _model.timepoint = @(time * 1000);
    _isCheckNetDown = NO;
    RJLoadView * loadView = [[RJLoadView alloc] initWithFrame:self.view.bounds];
    //@"http://xsscd.xicp.net:5100/smartadmin/forecast/getForecastAudit"
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].GetForecastAudit data:@{@"cityCode":cityCode,@"timePoint":_model.timepoint} completeBlock:^(id responseObject) {
        NSDictionary * data = responseObject[@"data"];
        [_model setCheckData:data];
        if (data[@"isDone"]) {
            [self setDataWithPage:_model.currentPage];
        }
        [loadView removeSelf];
        _isCheckNetDown = YES;
    }failBlack:^(id response) {
        
    }];
}


- (RJOutCityView *)getCityTable
{
    if (!_cityTable) {
        CGFloat width = 70;
        CGFloat height = 50;
        _cityTable = [[RJOutCityView alloc] initWithFrame:CGRectMake(ScreenWidth - width, 0, width, height)];
        [_cityTable setDelegate:self];
        [_cityTable.image removeFromSuperview];
    }
    return _cityTable;
}

- (RJWarningSectionView *)getSectionView
{
    if (!_sectionView) {
        CGFloat width = ScreenWidth / 2;
        _sectionView = [[RJWarningSectionView alloc] initWithFrame:CGRectMake(width / 2, 0, width, 30) titles:@[@"人工预报",@"预报审核"]];
        [_sectionView setDelegate:self];
    }
    return _sectionView;
}

- (RJWarningTypeSection *)getTypeSection
{
    if (!_typeSection) {
        _typeSection = [[RJWarningTypeSection alloc] initWithFrame:CGRectMake(0, 20, ScreenWidth, 40) titles:@[@"PM2.5",@"AQI",@"首要污染物"]];
        [_typeSection setDelegate:self];
    }
    return _typeSection;
  
}

- (UIButton *)getSendButton
{
    if (!_sendButton) {
        _sendButton = [[UIButton alloc] initWithFrame:CGRectMake(0, ScreenHeight - 50, ScreenWidth, 50)];
        [_sendButton setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"navBarBack"]]];
        [_sendButton setTitle:(_isCheck ? @"审核":@"提交") forState:UIControlStateNormal];
        [_sendButton.titleLabel setTextColor:[UIColor whiteColor]];
        [_sendButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
        [_sendButton.titleLabel setFont:[UIFont systemFontOfSize:30]];
        [_sendButton addTarget:self action:(_isCheck?@selector(pressCheckButton:) :@selector(pressSendButton:) )forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButton;
}

- (UILabel *)getCityLabel
{
    if (!_cityLabel) {
        _cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 51, ScreenWidth, 18)];
        [_cityLabel setFont:[UIFont systemFontOfSize:14]];
        [_cityLabel setTextColor:[UIColor whiteColor]];
        [_cityLabel setTextAlignment:NSTextAlignmentLeft];
        [_cityLabel setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"homeTableCellBack"]]];
        NSString * cityString = [NSString stringWithFormat:@" %@",[RJUserData defaultRJUserData].currentCity];
        [_cityLabel setText:cityString];
    }
    return _cityLabel;
}

#pragma mark - function
/**更改当前的滚动视图*/
- (void)changeScrollViewWithCount:(NSUInteger)count
{
    //保存前一个页面数据
    [self updateCurrentPageUserData];
    [_scrollView removeFromSuperview];
    
    //切换页面
    _scrollView = (_isCheck ?[self getCheckScrollViewWithCount:count] :[self getScrollViewWithCount:count]);
    if (_isCheck) {
        [_scrollView setContentSize:CGSizeMake(ScreenWidth, count == 0 ?600 : (count == 1) ? 800 : 700)];
    } else {
        [_scrollView setContentSize:CGSizeMake(ScreenWidth, count == 0 ?750 : (count == 1) ? 600 : 600)];
    }
    [self.mainView addSubview:_scrollView];
    if(_isCheck){
        if (_isCheckNetDown) {
            [self setDataWithPage:count];
        }
    } else {
        if (_isWarningNetDown) {
            [self setDataWithPage:count];
        }
    }
}
/**保存当前页面数据*/
- (void)updateCurrentPageUserData
{
    if ([RJUserData defaultRJUserData].isAudit) {
        return;
    }
    
    [_scrollView WarningFatherWillRemoveSelf];
    if (_isCheck) {
        if (_isChangeSection){
            [_model.warningUserData addEntriesFromDictionary:[_scrollView getData]];
            return;
        }
        [_model.checkUserData addEntriesFromDictionary:[_scrollView getData]];
    } else {
        if (_isChangeSection){
            [_model.checkUserData addEntriesFromDictionary:[_scrollView getData]];
            return;
        }
        [_model.warningUserData addEntriesFromDictionary:[_scrollView getData]];
    }
}

/**预警界面*/
- (RJWarningFather *)getScrollViewWithCount:(NSUInteger)count
{
    CGRect rect = CGRectMake(0, 65, ScreenWidth, ScreenHeight - 115);
    RJWarningFather * scrollView;
    switch (count) {
        case 0:
            scrollView =  [[RJWarningTable alloc] initWithFrame:rect];
            break;
        case 1:
            scrollView =  [[RJWarningAQIView alloc] initWithFrame:rect];
            break;
        case 2:
            scrollView =  [[RJWarningFirstView alloc] initWithFrame:rect];
            break;
        default:
            break;
    }
    return scrollView;
}

/**设置数据*/
- (void)setDataWithPage:(NSUInteger)pageNum
{
    switch (pageNum) {
        case 0:
            [_scrollView setData:(_isCheck ? _model.checkPM25PageData:_model.warningPM25PageData)];
            break;
        case 1:
            [_scrollView setData:(_isCheck ? _model.checkAQIPageData:_model.warningAQIPageData)];
            break;
        case 2:
            [_scrollView setData:(_isCheck ? _model.checkFirstPageData:_model.warningFirstPageData)];
            break;
        default:
            break;
    }
    
    //更新用户操作的数据
    if ([RJUserData defaultRJUserData].isAudit) {
        return;
    }
    
    if (_isCheck) {
        [_scrollView setUserData:_model.checkUserData];
    } else {
        [_scrollView setUserData:_model.warningUserData];
    }
}

- (RJWarningFather *)getCheckScrollViewWithCount:(NSUInteger)count
{
    CGRect rect = CGRectMake(0, 65, ScreenWidth, ScreenHeight - 115);
    RJWarningFather * scrollView;
    switch (count) {
        case 0:
            scrollView =  [[RJWarningPM25CheckView alloc] initWithFrame:rect];
            break;
        case 1:
            scrollView =  [[RJWarningAQICheckView alloc] initWithFrame:rect];
            break;
        case 2:
            scrollView =  [[RJWarningFirstCheckView alloc] initWithFrame:rect];
            break;
        default:
            break;
    }
    return scrollView;
}

#pragma mark - event
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [_cityTable setViewFrame:NO];
}

- (void)pressSendButton:(UIButton *)sender
{
    [_model getAllWarningData];
    if ([RJUserData defaultRJUserData].isAudit) {
        [RJTools showTitle:@"已经审核" msg:@"本日数据已经审核！" cancelString:@"确定" vc:self];
    } else {
        [self updateCurrentPageUserData];
        if ([_model checkWarningUserDataCompletion]) {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"确认" message:@"确认提交个人预报吗？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:cancelAction];
            UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self sendWarningData];
            }];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            [RJTools showTitle:@"信息不完整" msg:@"提交信息不完整！" cancelString:@"确定" vc:self];
        }
    }
}

- (void)sendWarningData
{
    NSDictionary * data = [_model getAllWarningData];
    RJLoadView * loadView = [[RJLoadView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:loadView];
//@"http://xsscd.xicp.net:5100/smartadmin/forecast/saveForecast"
//    [NetURL defaultURL].SaveForecast
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].SaveForecast data:data completeBlock:^(id responseObject) {
        [RJUserData defaultRJUserData].isDone = YES;
        NSDictionary * msg = responseObject[@"data"];
        [loadView removeFromSuperview];
        [RJTools showTitle:@"信息" msg:msg[@"message"] cancelString:@"确定" vc:self];
    }failBlack:^(id response) {
        [loadView removeFromSuperview];
    }];
}

- (void)pressCheckButton:(UIButton *)sender
{

    if([RJUserData defaultRJUserData].isAudit) {
        [RJTools showTitle:@"已经审核" msg:@"您今日已经审核过了！" cancelString:@"知道了" vc:self];
    } else {
        [self updateCurrentPageUserData];
        if ([_model checkCheckUserDataCompletion]) {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"确认" message:@"请确认信息无误的情况下提交审核，审核后将不可更改！" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:cancelAction];
            UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self sendCheckData];
            }];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            [RJTools showTitle:@"信息不完整" msg:@"提交信息不完整！" cancelString:@"确定" vc:self];
        }
    }
}

- (void)sendCheckData
{
    NSDictionary * data = [_model getAllCheckData];
    RJLoadView * loadView = [[RJLoadView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:loadView];
//@"http://xsscd.xicp.net:5100/smartadmin/forecast/saveForecastAudit"
//    [NetURL defaultURL].SaveForecastAudit
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].SaveForecastAudit data:data completeBlock:^(id responseObject) {
        NSDictionary * msg = responseObject[@"data"];
        [loadView removeFromSuperview];
        [RJTools showTitle:@"信息" msg:msg[@"message"] cancelString:@"确定" vc:self];
    }failBlack:^(id response) {
        
    }];
}
#pragma mark - RJMainSuperDelegate
- (void)RJMainSuperVCFreeAll
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WarningTextShow" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WarningTextFiledHide" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self  name:@"WarningGetAllCitys" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"touchScrollView" object:nil];
}

#pragma mark - RJCityTableDelegate
- (void)didSelectedRow:(NSUInteger)rowNumber data:(NSDictionary *)data
{
    _isChangeSection = YES;
    _model.currentCityCode = _model.cityCodes[rowNumber];
    _model.warningUserData = [NSMutableDictionary dictionary];
    _model.checkUserData = [NSMutableDictionary dictionary];
    [self initForecastNetWithCityCode:_model.currentCityCode];
    [[self getCityLabel] setText:[NSString stringWithFormat:@" %@",[[data allValues] lastObject]]];
}

- (void)didPressCityBar:(BOOL)isShow
{
//    CGRect rect = self.mainView.frame;
//    if (isShow) {
//        rect.origin.x = - (ScreenWidth / 4 + 5);
//    } else {
//        rect.origin.x = 0;
//    }
//    
//    [UIView animateWithDuration:0.3 animations:^{
//        [self.mainView setFrame:rect];
//    }];
}

#pragma mark - RJWarningTypeSectionDelegate
- (void)WarningTypeSection:(RJWarningTypeSection *)section didSelectCount:(NSUInteger)count
{
    _isChangeSection = NO;
    _model.currentPage = count;
    [self changeScrollViewWithCount:count];
}

#pragma mark - RJWarningSectionDelegate
- (BOOL)WarningSection:(RJWarningSectionView *)sectionView didSelected:(NSUInteger)count
{
    
    if (count == 0) {
        _isCheck = NO;
        _isCheckNetDown = NO;
    } else {
        //未提交预警的人无法审核
//        if ([RJUserData defaultRJUserData].isDone) {
            _isCheck = YES;
            [self initForecastAuditNetWithCityCode:_model.currentCityCode];
//        } else {
//            [RJTools showTitle:@"提示" msg:@"您还未提交个人预报信息！" cancelString:@"我知道了" vc:self];
//            return NO;
//        }
    }
    _isChangeSection = YES;
    [self changeScrollViewWithCount:_typeSection.currentPage];
    [_sendButton removeFromSuperview];
    _sendButton = nil;
    [self.view addSubview:[self getSendButton]];
    return YES;
    
}

#pragma mark - Notification
- (void)getAllCitys:(NSNotification *)data
{
    [_cityTable setData:data.object[@"citys"]];
}

- (void)WarningTextFiledShow:(NSNotification *)data
{
    CGFloat y = [data.userInfo[@"textBottomY"] floatValue];
    CGFloat contenOffSetY = _scrollView.contentOffset.y;
    _textFiledLength = sysNavBarHeight +  _scrollView.frame.origin.y + y - contenOffSetY;
}

- (void)WarningTextFiledHide:(NSNotification *)data
{
    [UIView animateWithDuration:0.2 animations:^{
        [_scrollView setContentOffset:CGPointMake(0, _scrollViewY)];
    }];
}

- (void)keyboardWasShow:(NSNotification*)aNotification
{
    if (!_lockChange) {
        _lockChange = YES;
        NSDictionary* info = [aNotification userInfo];
        CGFloat keyBoardHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        CGFloat length = (_textFiledLength + keyBoardHeight - ScreenHeight);
        _scrollViewY = _scrollView.contentOffset.y;
        if (length > 0) {
            CGPoint point = CGPointMake(_scrollView.contentOffset.x, _scrollView.contentOffset.y + length);
            [UIView animateWithDuration:0.2 animations:^{
                [_scrollView setContentOffset:point];
            }];
        }
    } else {
        _lockChange = NO;
    }
}

- (void)touchScrollView
{
    [_cityTable setViewFrame:NO];
}

@end
